import { writeFileSync } from 'fs'
import { resolve } from 'path'
import fetch from 'cross-fetch'
import stylelint from 'stylelint'
import chalk from 'chalk'
import { createLogger } from '../logger'

const cwd = process.cwd()
const logger = createLogger('info', { prefix: '[Gen iconfont]' })

export const run = (url: string, dir: string) => {
  try {
    const targetFilePath = resolve(cwd, dir)
    logger.info(`开始从 "${url}" 中读取内容`)
    fetch(url)
      .then(res => res.text())
      .then((response) => {
        const matches = String(response).match(/@font-face/)
        if (!matches) {
          throw new Error(`未知链接: "${url}"`)
        }

        writeFileSync(targetFilePath, response)
        logger.info(chalk.green(`已成功将 iconfont 内容写入 "${targetFilePath}" 中`))
      })
      .then(() => {
        logger.info('开始执行 stylelint')
        stylelint.lint({
          configBasedir: resolve(cwd, 'stylelintrc.json'),
          files: targetFilePath
        }).then(() => logger.info(chalk.green('执行 stylelint 完成')))
      })
  } catch (err) {
    const { message } = err as Error
    logger.error(chalk.red(`${message}`))
    process.exit(1)
  }
}
